<template>
  <div class="update-photo">
    <img class="img" ref="img" :src="img" />
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>
<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  components: {},
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data() {
    return {
      cropper: null
    }
  },
  computed: {},
  watch: {},
  methods: {
    onConfirm() {
      // 基于服务器的裁剪使用，getData 方法获取裁切参数
      // console.log(this.cropper.getDate())

      // 纯客户端的裁切使用 getCroppedCanvas 获取裁切的文件对象
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        try {
          // 如果接口要求 Content-Type是 multipart/form-data
          // 则你必须传递 FormData对象
          const formData = new FormData()
          formData.append('photo', blob)

          const { data } = await updateUserPhoto(formData)
          console.log(data)
          // 关闭弹出层
          this.$emit('close')
          // 更新视图
          this.$emit('update-photo', data.data.photo)
        } catch (err) {
          this.$emit.fail('头像修改失败')
        }
      })
    }
  },
  created() {},
  mounted() {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 查看模式，固定裁剪框不能出图片
      dragMode: 'move', // 拖动模式，拖动图片，遮罩区不动
      aspectRatio: 1, // 截图比例
      autoCropArea: 1, // 自动截取区域
      cropBoxMovable: false, // 截图区域是否可以移动
      cropBoxResizable: false, // 截图区域是否可以缩放
      background: false, // 背景
      movable: true // 画布是否可以移动
    })
  }
}
</script>
<style scoped lang="less">
.update-photo {
  background-color: #000000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #ffffff;
    }
  }
  .img {
    display: block;
    max-width: 100%;
  }
}
</style>
